/**
启动
*/
initIsStop(function(isStop) {
    if (isStop) {
        return;
    }

    initWordList(start);
});

var wordList = [];

function start(allWordList) {
    wordList = allWordList;
    addTextToSpan($("body"));

    bindWordEvent();
}
/**
鼠标移入翻译
*/
var $currentTips = null;

function bindWordEvent() {

    //绑定点击事件为熟词
    $("span.new_word").click(function() {
        var word = $(this).attr("word");
        chrome.runtime.sendMessage({ action: "putWordToSever", data: word },
            function(response) {
                $("span[word='" + word + "']").removeClass("new_word");
            });

    });

    //绑定翻译事件
    var tip = $("span.new_word").mouseenter(function() {
        var $curentWord = $(this);

        if ($currentTips != null && $currentTips.length != 0) {
            $currentTips.click();
        }
        chrome.runtime.sendMessage({ action: "translation", data: $curentWord.attr("word") },
            function(word) {
                $currentTips = $curentWord.tips({
                    side: 3,
                    msg: wordFanyiHtml(word),
                    bg: '#B8860B',
                    time: 1
                });
            });

    });
}

/**
将单词用span包裹
*/
var listNotSpan = ["SCRIPT", "STYLE", "LINK"];

function addTextToSpan($parent) {

    //递归子元素
    $parent.children().each(function() {
        var flag = true;
        for (var i = 0; i < listNotSpan.length; i++) {
            if (this.nodeName == listNotSpan[i]) {
                flag = false;
                break;
            }
        }
        if (flag) {
            addTextToSpan($(this));
        }
    });
    //遍历元素 将单词用一个特殊的span包裹
    $parent.contents().filter(function() {
        if (this.nodeType == 3 && !isBlank(this.wholeText)) {
            var $textNode = $(this);
            $textNode.before(handlerWords(this.data));
            $textNode.remove();
            return true;
        } else {
            return false;
        }
    });
}

/**
处理单词为单词添加class
*/
function handlerWords(text) {
    var words = text.split(/([a-zA-Z]+)/g);
    var newHtmlText = '';
    for (var i = 0; i < words.length; i++) {

        if (checkEnglish(words[i])) {
            words[i] = getWordSpan(words[i]);
        }
        newHtmlText = newHtmlText + " " + words[i];
    }
    return newHtmlText;
}

function getWordSpan(word) {

    if (isOldWord(word)) {
        //return "<span class='old_word' word='"+ word +"'>"+ word +"</span>";
        return word;
    } else {
        return "<span class='new_word' word='" + word.toLowerCase() + "'>" + word + "</span>";
    }
}

/**
检测是否为英文单词 (小于2个长度的 为中文不翻译)
*/
function checkEnglish(word) {
    return word.match(/[a-zA-Z]{3,}/);
}

/**
判断是否为空
*/
function isBlank(obj) {
    return (!obj || $.trim(obj) === "");
}

/**
是否已经认识该单词
*/
function isOldWord(word) {
    word = word.toLowerCase()
    for (var i = 0; i < wordList.length; i++) {
        if (wordList[i] == word) {
            return true;
        }
    }
    return false;
}

/**
获取单词列表
*/
function initWordList(func) {
    chrome.runtime.sendMessage({ action: "getWordList" },
        function(wordList) {
            func(wordList)
        });
}

function initIsStop(func) {
    chrome.runtime.sendMessage({ action: "getStopFlag" },
        function(isStop) {
            func(isStop);
        });
}

function wordFanyiHtml(word) {
    var html = '<div><div>有道词典结果</div><br><br>';
    if (word.basic) {
        for (var i = 0; i < word.basic.explains.length; i++) {
            html = html + '<p>' + word.basic.explains[i] + '</p>';
        }
    } else {
        html = html + "<p>不是词语</p>";
    }
    html = html + "</div>";
    return html;
}
